package com.example.musicplayer;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class MainActivity extends Activity {
    private Context mContext;
    private List<Music> mData =null;
    private  MusicAdapter mAdapter =null;
    private ListView list_music;
    private TextView textView;
    private ImageButton start;
    private ImageButton stop;
    private ImageButton pause;
    private ImageButton next;
    private ImageButton last;
    private SeekBar seekBar;
    private MediaPlayer myMediaPlayer;
    private List<Music> myMusicList=new LinkedList<>();
    private int currentListItem=0;

    PermissionHelper permissionHelper = new PermissionHelper();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textview);
        start = findViewById(R.id.start);
        stop = findViewById(R.id.stop);
        next = findViewById(R.id.next);
        pause = findViewById(R.id.pause);
        last = findViewById(R.id.last);
        seekBar = findViewById(R.id.seekBar);
        list_music=findViewById(R.id.musicLv);
        list_music.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentListItem = position;
                playMusic(myMusicList.get(currentListItem).getPath());
                Toast.makeText(MainActivity.this,"song",Toast.LENGTH_SHORT).show();
            }
        });
        myMediaPlayer = new MediaPlayer();
        asdPermission();
    }
    Handler handler = new Handler();
    Runnable updateThread = new Runnable() {
        public void run() {
            if (myMediaPlayer != null) {
                seekBar.setProgress(myMediaPlayer.getCurrentPosition());//另开线程更新进度条
                handler.postDelayed(updateThread, 100);//使用PostDelayed方法，一秒后调用此Runnable对象
            }
        }
    };

    void musicList(){
        Cursor cursor = getContentResolver()
                .query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                        , null, null, null,
                        MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        if (cursor != null) {
            mData = new LinkedList<>();
            while (cursor.moveToNext()){
                String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                String song = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                String singer = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                int icon = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                Music music = new Music();
                myMusicList.add(new Music(path,song,singer,icon));
                music.setSong(song);
                music.setSinger(singer);
                music.setIcon(icon);
                mData.add(music);
            }
            mContext=MainActivity.this;
            mAdapter = new MusicAdapter((LinkedList<Music>)mData,mContext);
            list_music.setAdapter(mAdapter);
        }else{
            Toast.makeText(MainActivity.this, "没有音乐",Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }

    void listener(){
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(myMediaPlayer.isPlaying()){
                    myMediaPlayer.reset();
                    seekBar.setProgress(0);
                    seekBar.setEnabled(true);
                }
                textView.setText("停止");
            }
        });

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playMusic(myMusicList.get(currentListItem).getPath());
                textView.setText("播放");
            }
        });
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextMusic();
                textView.setText("下一首");
            }
        });

        pause.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(myMediaPlayer.isPlaying()){
                    myMediaPlayer.pause();
                    seekBar.setEnabled(false);
                }else{
                    myMediaPlayer.start();
                    seekBar.setEnabled(true);
                }
                textView.setText("暂停");
            }
        });

        last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lastMusic();
                textView.setText("后一首");
            }
        });
    }
    void playMusic(String path){
        try {
            myMediaPlayer.reset();
            myMediaPlayer.setDataSource(path);
            myMediaPlayer.prepare();
            myMediaPlayer.start();
            myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    myMediaPlayer.start();
                    start.setEnabled(false);
                    start.setClickable(false);
                    seekBar.setMax(myMediaPlayer.getDuration());
                    handler.post(updateThread);
                    seekBar.setEnabled(true);
                }
            });
            myMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    nextMusic();
                    seekBar.setProgress(0);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    void nextMusic(){
        if(++currentListItem >= myMusicList.size()){
            currentListItem=0;
        }
        else{
            playMusic(myMusicList.get(currentListItem).getPath());
        }
    }

    void lastMusic(){
        if(currentListItem!=0)
        {
            if(--currentListItem>=0){
                currentListItem = myMusicList.size();
            } else{
                playMusic(myMusicList.get(currentListItem).getPath());
            }
        }  else{
            playMusic(myMusicList.get(currentListItem).getPath());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            myMediaPlayer.stop();
            myMediaPlayer.release();
            this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    public void asdPermission(){
        permissionHelper.checkPermission(this, new PermissionHelper.AskPermissionCallBack() {
            @Override
            public void onSuccess() {
                musicList();
                listener();
            }
            @Override
            public void onFailed() {
            }
        });
    }

}
